package store;

import parser.Content;
import util.MyEmailUtil;

import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailStore implements Store {
    @Override
    public boolean store(List<Content> contentList, Properties properties) throws Exception {

        String keywords = properties.getProperty("keywords");
        String[] newKeyword = keywords.split(",");

        String email = properties.getProperty("email");
        String subject = "来自Java的提醒";
        StringBuilder text = new StringBuilder();


        for (String keyword : newKeyword) {
            int count = 0;
            Pattern pattern = Pattern.compile(keyword);
            StringBuilder contentText = new StringBuilder();

            for (Content content : contentList) {
                Matcher matcher = pattern.matcher(content.getText());
                if (matcher.find()) {
                    count++;
                    contentText.append(content.getText()).append("<br>");
                    contentText.append("http://bbs.xmfish.com/").append(content.getUrl()).append("<br>");
                    contentText.append(content.getDate()).append("<br>");
                }
            }
            if (count > 0) {
                text.insert(0, "共命中关键词： " + keyword + " " + count + "条<br>");
                text.append(contentText);
            }
            contentText.delete(0, contentText.length());
            count = 0;
        }

        //发送邮件
        if (!contentList.isEmpty()) {
            MyEmailUtil.send(email, subject, text.toString());
            return true;
        } else return false;
    }
}
